package org.jarraiders.musiclibrary.client.presenter;

import org.jarraiders.musiclibrary.client.ArtistsServiceAsync;
import org.jarraiders.musiclibrary.client.event.ArtistUpdatedEvent;
import org.jarraiders.musiclibrary.client.event.EditArtistCancelledEvent;
import org.jarraiders.musiclibrary.shared.domain.ArtistDTO;

import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.dom.client.HasClickHandlers;
import com.google.gwt.event.shared.HandlerManager;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.HasValue;
import com.google.gwt.user.client.ui.HasWidgets;
import com.google.gwt.user.client.ui.Widget;

public class EditArtistPresenter implements Presenter {

	public interface Display {
		HasClickHandlers getSaveButton();

		HasClickHandlers getCancelButton();

		HasValue<String> getArtistName();

		Widget asWidget();
	}

	private ArtistDTO artist;
	private final ArtistsServiceAsync rpcService;
	private final HandlerManager eventBus;
	private final Display display;

	public EditArtistPresenter(ArtistsServiceAsync rpcService, HandlerManager eventBus, Display display) {
		this.rpcService = rpcService;
		this.eventBus = eventBus;
		this.artist = new ArtistDTO();
		this.display = display;
		bind();
	}

	public EditArtistPresenter(ArtistsServiceAsync rpcService, HandlerManager eventBus, Display display, String id) {
		this.rpcService = rpcService;
		this.eventBus = eventBus;
		this.display = display;
		bind();

		rpcService.getArtist(id, new AsyncCallback<ArtistDTO>() {
			public void onSuccess(ArtistDTO result) {
				artist = result;
				EditArtistPresenter.this.display.getArtistName().setValue(artist.getArtistName());

			}

			public void onFailure(Throwable caught) {
				Window.alert("Error retrieving contact");
			}
		});

	}

	public void bind() {
		this.display.getSaveButton().addClickHandler(new ClickHandler() {
			public void onClick(ClickEvent event) {
				doSave();
			}
		});

		this.display.getCancelButton().addClickHandler(new ClickHandler() {
			public void onClick(ClickEvent event) {
				eventBus.fireEvent(new EditArtistCancelledEvent());
			}
		});
	}

	@Override
	public void go(final HasWidgets container) {
		container.clear();
		container.add(display.asWidget());
	}

	private void doSave() {
		artist.setArtistName(display.getArtistName().getValue());

		rpcService.updateArtist(artist, new AsyncCallback<ArtistDTO>() {
			public void onSuccess(ArtistDTO result) {
				eventBus.fireEvent(new ArtistUpdatedEvent(result));
			}

			public void onFailure(Throwable caught) {
				Window.alert("Error updating contact");
			}
		});
	}

}
